import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn import preprocessing, svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split, GridSearchCV

from example import utilities

# 预处理数据
df = pd.read_csv("../data/20240808.csv", encoding="UTF-8",
                 usecols=["比赛时间", "联赛", "0临", "1临", "2临", "3临", "4临", "5临", "6临", "7临", "总进球"],
                 header=0,
                 low_memory=False,
                 dtype={"0临": float, "1临": float, "2临": float, "3临": float, "4临": float, "5临": float,
                        "6临": float, "7临": float, "总进球": float})
df = df.dropna()

start_date = "2023-01-01"
end_date = "2024-07-01"
league = "日职"

df['比赛时间'] = pd.to_datetime(df['比赛时间'])
df = df[(df['比赛时间'] >= start_date) & (df['比赛时间'] <= end_date)]
if league != "":
    df = df[df['联赛'] == league]

label_encoder1 = preprocessing.LabelEncoder()
encode_result = label_encoder1.fit_transform(df['联赛'])
df['联赛'] = encode_result

X = df.drop(["比赛时间", "总进球"], axis=1)
y = df["总进球"]

# params = {'kernel': 'linear'}
# # params = {'kernel': 'poly', 'degree': 8}
# # params = {'kernel': 'rbf'}
# classifier = SVC(**params)
# classifier.fit(X_train, y_train)
# y_test_pred = classifier.predict(X_test)
#

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=5)
X_test_coef = X_test
X_train = X_train.drop(["0临","2临", "3临", "4临", "5临", "6临", "7临"], axis=1)
X_test = X_test.drop(["0临","2临", "3临", "4临", "5临", "6临", "7临"], axis=1)

# # Set the parameters by cross-validation
parameter_grid = [{'kernel': ['linear']},
                  {'kernel': ['poly'], 'degree': [2, 3, 4, 5, 6, 7, 8]},
                  {'kernel': ['rbf'], 'gamma': [0.01, 0.001, 0.0001], 'C': [1, 10, 50, 600]},
                  ]

metrics = ['accuracy']
for metric in metrics:
    print("\n#### Searching optimal hyperparameters for", metric)

    classifier = GridSearchCV(SVC(),
                              parameter_grid, cv=4, scoring=metric, return_train_score=True)
    classifier.fit(X_train, y_train)

    # print ("\nScores across the parameter grid:")
    # for params, avg_score, _ in classifier.grid_scores_:
    #     print (params, '-->', round(avg_score, 3))

    print("\nHighest scoring parameter set:", classifier.best_params_, classifier.best_score_)

    cf = classifier.best_estimator_
    y_true, y_pred = y_test, cf.predict(X_test)
    # print("\nFull performance report:\n")
    # print(classification_report(y_true, y_pred))

    accuracy = accuracy_score(y_true.values, y_pred)
    print(f"\naccuracy:{accuracy}\n")

    total = 0
    bonus = 0
    for i in range(len(X_test)):
        x = X_test_coef.values[i]
        pred_num = int(y_pred[i])
        true_num = int(y_true.values[i])
        coef = x[int(true_num) + 1]
        coef_pred = x[int(pred_num) + 1]
        # if coef_pred<4:
        #     continue
        total += 1
        got = False
        if (pred_num == true_num):
            bonus += coef
            got = True
        print(f'total:{total} bonus:{round(bonus, 2)} 预测:{pred_num}球 实际:{true_num}球 {coef} {"中" if got else ""}')
        pass
